package com.weim.weim.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;


/**
 * @author wangxiaochen
 * @date 2019/12/19
 */
public class ImgCompress {
    private static final Logger log = LoggerFactory.getLogger(ImgCompress.class);

    //封面缩略图大小
    public static final int IMAGE_SIZE=32768;
    private static int THUMBNAIL_IMG_SIZE=200*1024;
    private static int IMG_SIZE=1024*1024;
    /***
     * 生成封面
     * @param sourceImage,srcFileSize
     * @return
     */
    public static byte[] imgCover(BufferedImage sourceImage) throws Exception {
        try {
            return commpressBufferedImage(sourceImage);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            throw ex;
        }
    }

    /**
     * @Description: 压缩图片到指定大小
     * @Param:  desFileSize：大小，accuracy：每次缩小几倍
     * @return:  String
     * @Author: zzy
     * @Date: 2019/9/29
     */
    public static byte[] commpressBufferedImage(BufferedImage image) throws IOException {
        byte[] byteTo=null;
        ByteArrayOutputStream baos =null;
        ByteArrayInputStream bais = null;
        try {
            baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
        ImageIO.write(image, "jpg", baos);
        byteTo = baos.toByteArray();
        } catch (IOException e) {
            log.error("字节流异常",e);
        }finally {
            if(bais !=null) {
                bais.close();
            }
            if(baos !=null) {
                baos.close();
            }
        }
        return byteTo;
    }
}